package server;

import helper.Log;

import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.util.SortedSet;
import java.util.TreeSet;

import remote.RemoteSpelling;

/**
 * Server for RMISpelling implementation
 * 
 * @author the_james_marq
 * @version 28 October 13
 */
public class RMISpellingServer implements RemoteSpelling {
      
	/**
	 * Word list used for methods.
	 */
    private WordList word_list;
	
    /**
     * Constructor for RMISpellingServer
     * 
     * @param filename the path to the dictionary file
     */
	public RMISpellingServer(String filename){
		        
        try {
			word_list = new WordList(filename);
		} catch (IOException e) {
			Log.err("Could not open file.");
		}
		
	}
	
	/**
	 * Main method for RMI server.
	 * 
	 * @param args command line arguments
	 */
    public static void main(String args[]) {
        
    	try {
            RMISpellingServer obj = new RMISpellingServer(args[2]);
            RemoteSpelling stub = 
            		(RemoteSpelling) UnicastRemoteObject.exportObject(obj, 0);

            // Bind the remote object's stub in the registry
            LocateRegistry.createRegistry(Integer.parseInt(args[0]));
            
            Registry registry = LocateRegistry.getRegistry(Integer.parseInt(args[0]));
            registry.bind(args[1], stub);

            Log.out("Exported spelling service as " + args[1] + " on registry port" +
            		" " + args[0]);
        } catch (Exception e) {
            Log.err("Could not create registry.");
        }
        
    }
    
    /**
     * {@inheritDoc}
     */
	@Override
	public SortedSet<String> check(String the_word) throws RemoteException {
		Log.out("Received query (" + the_word + ")");
		
		SortedSet<String> ret_set = new TreeSet<String>();

		if(word_list.isInList(the_word)) {
			Log.out(the_word + " is spelled correctly.");
			return null;
		} else {
			String ret_str = the_word + " is spelled incorrectly. ";
			ret_set.addAll(word_list.getCloseWords(the_word));

			if(!(ret_set.size() > 1)) {
				ret_str += "No suggestions.";
			} else {
				ret_str += ret_set.size() + " suggestions: ";
				for(String s : ret_set) {
					if(s.equals("FALSE")) {continue;}
					else {
						ret_str += s + " ";
					}
				}
			}
			
			Log.out(ret_str);
		}
		return ret_set;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void add(String the_word) throws RemoteException {
		if(word_list.add(the_word)){
			Log.out(the_word + " has been added.");
		} else {
			Log.out(the_word + " was already in the dictionary.");
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void remove(String the_word) throws RemoteException {
		if(word_list.remove(the_word)) {
			Log.out(the_word + " has been removed.");
		} else {
			Log.out(the_word + " was not in the dictionary.");
		}
	}
}